import express from 'express';
import cors from 'cors'
import { WebSocketServer } from 'ws'

const app = express()

app.use(cors())


const server = app.listen(3000,() => {
    console.log('服务启动');
})

// 初始化ws服务
const wss = new WebSocketServer({server})

const connection = {}

wss.on('connection',(ws) => {
    console.log('有新的连接');
    // socket传输只能字符串或者buffer
    ws.on('message',(message) => {
      const data = JSON.parse(message)
      if (data.action === 'login') {
        if (connection[data.id] && connection[data.id].fingerprint) {
          console.log('新设备登录');
          
          // 新设备登录

          connection[data.id].socket.send(JSON.stringify({
            action: 'logout',
            message: `您的账号在其他设备登录 ${new Date().toLocaleString()}`,
          }))
          connection[data.id].socket.close()
          connection[data.id].socket = ws

        }else {
          console.log('第一次登录');
          
          // 第一次登录
          connection[data.id] = {
            socket: ws,
            fingerprint: data.fingerprint
          }
        }
      }
    })
})
